import { realTimeMonitoringControllerGlcOverview } from '@/services/ess/realTimeMonitoring';
import { Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { useDeviceInfo, useIsFresh, useSelectedDeviceNode } from '../SelectedDeviceNodeContext';
import { Overview } from './Overview';
import { PieChart } from './PieChart';

// dataList
export const GLCTotal: React.FC = () => {
  const [pieInfo, setpieInfo] = useState<API.PcsDataDTO['statusList']>([]);
  const deviceNode = useSelectedDeviceNode();
  const { setDeviceInfo } = useDeviceInfo();
  const { isRefesh, setIsRefesh } = useIsFresh();
  const [loading, setLoading] = useState<boolean>(true);

  const fetchData = async () => {
    setLoading(true);
    realTimeMonitoringControllerGlcOverview({
      areaId: deviceNode?.areaId?.toString() ?? undefined,
      deviceCode: deviceNode?.deviceCode ?? undefined,
      deviceName: deviceNode?.deviceName ?? undefined,
      deviceType: deviceNode?.deviceType ?? undefined,
    }).then((res) => {
      setLoading(false);
      setDeviceInfo({
        ts: res?.data?.ts ?? undefined,
        onLine:
          res?.data?.onlineState || String(res?.data?.onlineState) === '0'
            ? String(res?.data?.onlineState)
            : undefined,
      });
      setpieInfo(res.data?.statusList);
    });
  };

  useEffect(() => {
    fetchData();
  }, [deviceNode]);

  useEffect(() => {
    if (isRefesh) {
      fetchData();
      setIsRefesh(false);
    }
  }, [isRefesh]);

  return (
    <Spin spinning={loading}>
      <div style={{ display: 'flex', height: '18rem', padding: '20px' }}>
        <PieChart pcsViewInfo={pieInfo}></PieChart>
      </div>
      <Overview />
    </Spin>
  );
};
